﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomsSystem.BLL;
using CustomsSystem.Common;
using System.Data;
using Maticsoft.Common;
using CustomsSystem.Model;
using Microsoft.Win32;

namespace WEB.contract
{
    public partial class ContractView : System.Web.UI.Page
    {
        ContractManage bll = new ContractManage();
        DataSet ds = new DataSet();
        protected void Page_Load(object sender, EventArgs e)
        {
            //载入数据
            if (!IsPostBack)
            {
                ds = bll.GetConList("");
                gvCon.DataSource = ds;
                gvCon.DataBind();
            }
            else
            {
                ds = bll.GetConList(ConQuery());
                gvCon.DataSource = ds;
            }

        }

        protected void gvCon_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            #region 按钮
            if (e.CommandName == "dow")//下载键
            {

                string index = e.CommandArgument.ToString();
                int id = (Int32)gvCon.DataKeys[Convert.ToInt32(index)].Value;
                string fileName = bll.GetModel(id).Images.ToString();//取得下载地址
                if (!System.IO.File.Exists(fileName))
                {
                    MessageBox.Show(this, "文件丢失！");
                }
                else
                {
                    //执行下载
                    if (System.IO.Path.GetExtension(fileName) == ".html")
                    {
                        fileName = fileName.Replace(".html", ".doc");
                    }
                    DownloadFile(fileName);//调用下载
                }

            }
            if (e.CommandName == "more")//更多键
            {
                string index = e.CommandArgument.ToString();
                int id = (Int32)gvCon.DataKeys[Convert.ToInt32(index)].Value;//取得该行的合同编号
                int cid = bll.GetModel(id).CID;//取得客户编号
                Response.Redirect("./OtherView.aspx?CID=" + cid);//更多合同页面

            }
            if (e.CommandName == "add")//添加键
            {
                string index = e.CommandArgument.ToString();
                int id = (Int32)gvCon.DataKeys[Convert.ToInt32(index)].Value;//取得该行的合同编号
                int cid = bll.GetModel(id).CID;//取得客户编号
                Response.Redirect("./Add.aspx?AddID=" + cid);//增加页面
            }
            #endregion
        }
        /// <summary>
        /// 行创建事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvCon_RowCreated(object sender, GridViewRowEventArgs e)
        {
            #region 到期合同判断
            if (e.Row.RowType == DataControlRowType.DataRow)//为数据行的就载入进入计算
            {
                //进入数据行时，改行还没有数据，只能读取上一行的数据
                if (gvCon.Rows.Count > 0)
                {
                    int index = e.Row.RowIndex - 1;
                    TableCellCollection th = gvCon.Rows[index].Cells;//取得数据行的单元格
                    DateTime Now = DateTime.Now;//现在时间
                    if (th[6].Text.ToString().Trim() != "")
                    {
                        DateTime Date = Convert.ToDateTime(th[6].Text);//取得结束日期
                        int i = (Convert.ToInt32(Date.Year) - Convert.ToInt32(Now.Year)) * 12;//年份相减
                        int j = (Convert.ToInt32(Date.Month) - Convert.ToInt32(Now.Month));//月份相减

                        if (i + j <= 1)
                        {
                            gvCon.Rows[index].ForeColor = System.Drawing.Color.Red;//最近一个月到期的文字为红

                        }

                    }
                }

            }
            //行尾读取最后一行数据
            if (e.Row.RowType == DataControlRowType.Footer)//为数据行的就载入进入计算
            {
                //进入数据行时，改行还没有数据，只能读取上一行的数据
                if (gvCon.Rows.Count > 0)
                {
                    int index = gvCon.Rows.Count - 1;
                    TableCellCollection th = gvCon.Rows[index].Cells;//取得数据行的单元格
                    DateTime Now = DateTime.Now;//现在时间
                    if (th[6].Text.ToString().Trim() != "")
                    {
                        DateTime Date = Convert.ToDateTime(th[6].Text);//取得结束日期
                        int i = (Convert.ToInt32(Date.Year) - Convert.ToInt32(Now.Year)) * 12;//年份相减
                        int j = (Convert.ToInt32(Date.Month) - Convert.ToInt32(Now.Month));//月份相减
                        
                        if (i + j <= 1)
                        {
                            gvCon.Rows[index].ForeColor = System.Drawing.Color.Red;//最近一个月到期的文字为红

                        }

                    }
                }

            }
            #endregion
        }
        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            #region 删除

            int id = Convert.ToInt32(((Button)(sender)).CommandArgument.ToString());//获取ID

            if (bll.Delete(id))//删除
            {
                MessageBox.ShowAndRedirect(this, "删除成功！", "./ContractView.aspx");

            }
            else
            {
                MessageBox.Show(this, "删除失败！");
            }

            #endregion

        }

        /// <summary>
        /// 搜索键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btQuery_Click(object sender, EventArgs e)
        {
            gvCon.DataBind();
        }

        /// <summary>
        /// 搜索判断
        /// </summary>
        /// <returns></returns>
        public string ConQuery()
        {
            if (tbQuery.Text.ToString().Trim() != "")//判断文本框是否为空值
            {
                string sql = ddlQuery.SelectedValue + " like'%" + tbQuery.Text.ToString().Trim() + "%'";
                return sql;
            }
            else
            {
                return " 1=1";
            }
        }

        /// <summary>
        /// 换页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvCon_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvCon.PageIndex = e.NewPageIndex;
            gvCon.DataBind();
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filename">文件物理地址</param>
        public void DownloadFile(string filename)
        {
            int intStart = filename.LastIndexOf(@"\") + 1;
            string saveFileName = filename.Substring(intStart, filename.Length - intStart);

            System.IO.FileInfo fi = new System.IO.FileInfo(filename);
            string fileextname = fi.Extension;
            string DEFAULT_CONTENT_TYPE = "application/unknown";
            RegistryKey regkey, fileextkey;
            string filecontenttype;
            try
            {
                regkey = Registry.ClassesRoot;
                fileextkey = regkey.OpenSubKey(fileextname);
                filecontenttype = fileextkey.GetValue("Content Type", DEFAULT_CONTENT_TYPE).ToString();
            }
            catch
            {
                filecontenttype = DEFAULT_CONTENT_TYPE;
            }
            Response.Clear();
            Response.Charset = "gb2312";
            Response.Buffer = true;
            this.EnableViewState = false;
            Response.ContentEncoding = System.Text.Encoding.Default;

            string encodefileName = System.Web.HttpUtility.UrlEncode(saveFileName, System.Text.Encoding.UTF8);
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + encodefileName);

            Response.ContentType = filecontenttype;

            Response.WriteFile(filename);
            Response.Flush();
            Response.Close();

            Response.End();
        }

        protected void ddlDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlDate.SelectedIndex == 0)
            {
                gvCon.DataBind();//默认
            }

            else if (ddlDate.SelectedValue == "1")
            {
                string sql = "";
                DateTime data = DateTime.Today;
                sql = " Dateover between  '" + data + "'  and  '" + data.AddMonths(1) + "'  and " + ConQuery() + " order by Dateover desc";//日期范围加搜索条件
                gvCon.DataSource = bll.GetConList2(sql);
                gvCon.DataBind();

            }

            else if (ddlDate.SelectedValue == "2")
            {
                string sql = "";
                sql = " Dateover < '" + DateTime.Today + "' and " + ConQuery() + " order by Dateover desc";//日期范围加搜索条件
                gvCon.DataSource = bll.GetConList2(sql);
                gvCon.DataBind();

            }

            else if (ddlDate.SelectedValue == "3")
            {
                string sql = "";
                sql = " Dateover > '" + DateTime.Today + "' and " + ConQuery() + " order by Dateover ";//日期范围加搜索条件
                gvCon.DataSource = bll.GetConList2(sql);
                gvCon.DataBind();

            }
        }
    }
}